﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

/// <summary>
///图像压缩类
/// </summary>
public class ImageCompression
{
    //*********************************************************************************************
    //*****************************************压缩图片函数*****************************************
    //***********************************************************************************************
    //sFile: 保存上传到服务器上的图片路径
    //dFile: 压缩后的新文件存放路径
    //dHeight 、 dWidth:  设置缩放比例，压缩后的分辨率， 宽、高分别设置（设置压缩后图片的分辨率） 
    // flag: 设置压缩比例,不改变分辨率，压缩图片
    /*
     *调用例子：
     *private Image ig;
     *string newPath = Server.MapPath("temp");
                    if (!Directory.Exists(newPath))
                    {
                        Directory.CreateDirectory(newPath);
                    }
     * newPath = newPath + "\\" + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + fileType;
                    FileUpload1.PostedFile.SaveAs(newPath);
                    ig = Image.FromFile(newPath);
                    Session["path"] = Server.MapPath("temp") + "\\" + DateTime.Now.Second + fileType; //保存上传到服务器上的图片路径
                    Session["spath"] = newPath;
                    GetPicThumbnail(newPath, Session["path"].ToString(),
                                    Convert.ToInt32(ig.Height*(Convert.ToDouble(ddlSize.SelectedItem.Text)/100)),
                                    Convert.ToInt32(ig.Width*(Convert.ToDouble(ddlSize.SelectedItem.Text)/100)),
                                    int.Parse(ddlCompress.SelectedItem.Text));
                    ig.Dispose();
     */
    public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag)
    {
        Image iSource = Image.FromFile(sFile);
        ImageFormat tFormat = iSource.RawFormat;
        int sW = 0, sH = 0;
        var tem_size = new Size(iSource.Width, iSource.Height);
        if (tem_size.Height > dHeight || tem_size.Width > dWidth)
        {
            if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
            {
                sW = dWidth;
                sH = (dWidth * tem_size.Height) / tem_size.Width;
            }
            else
            {
                sH = dHeight;
                sW = (tem_size.Width * dHeight) / tem_size.Height;
            }
        }
        else
        {
            sW = tem_size.Width;
            sH = tem_size.Height;
        }
        var oB = new Bitmap(dWidth, dHeight);
        Graphics g = Graphics.FromImage(oB);
        g.Clear(Color.WhiteSmoke);

        // 设置画布的描绘质量
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width,
                    iSource.Height, GraphicsUnit.Pixel);
        g.Dispose();

        // 以下代码为保存图片时，设置压缩质量
        var eP = new EncoderParameters();
        var qy = new long[1];
        qy[0] = flag;
        var eParam = new EncoderParameter(Encoder.Quality, qy);
        eP.Param[0] = eParam;
        try
        {
            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo对象。
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICIinfo = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICIinfo = arrayICI[x]; //设置JPEG编码
                    break;
                }
            }
            if (jpegICIinfo != null)
            {
                oB.Save(dFile, jpegICIinfo, eP);
            }
            else
            {
                oB.Save(dFile, tFormat);
            }
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            iSource.Dispose();
            oB.Dispose();
        }
    }
}

